<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register } from "@/api/user/register.ts";
import { User, Lock, ArrowRight, Check } from '@element-plus/icons-vue'

interface RegisterUser {
  username: string;
  password: string;
  confirmPassword: string;
}

const user = ref<RegisterUser>({
  username: '',
  password: '',
  confirmPassword: ''
})

const errorMessage = ref('')
const loading = ref(false)
const router = useRouter()

// 密码强度检测
const passwordStrength = ref(0)
const getPasswordStrength = (password: string) => {
  let strength = 0
  if (password.length >= 6) strength += 1
  if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength += 1
  if (password.match(/\d/)) strength += 1
  if (password.match(/[^a-zA-Z\d]/)) strength += 1
  return strength
}

const onPasswordChange = () => {
  passwordStrength.value = getPasswordStrength(user.value.password)
}

const handleSubmit = async (e: Event) => {
  e.preventDefault()
  errorMessage.value = ''

  if (!user.value.username.trim()) {
    errorMessage.value = '用户名不能为空'
    return
  }

  if (user.value.username.length < 3) {
    errorMessage.value = '用户名长度不能少于3位'
    return
  }

  if (user.value.password.length < 6) {
    errorMessage.value = '密码长度不能少于6位'
    return
  }

  if (user.value.password !== user.value.confirmPassword) {
    errorMessage.value = '两次输入的密码不一致'
    return
  }

  try {
    loading.value = true
    const res: any = await register(user.value.username, user.value.password)

    if (res.status === 201 || res.status === 200) {
      ElMessage.success('注册成功！')
      setTimeout(() => {
        router.push('/login')
      }, 1000)
    }
  } catch (error: any) {
    console.error('注册失败:', error)
    const errorText = error?.response?.data?.message || '注册失败，请稍后再试'
    errorMessage.value = errorText
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}
</script>

<template>
  <div class="auth-page">
    <!-- 背景装饰 -->
    <div class="bg-decoration">
      <div class="bg-shape bg-shape-1"></div>
      <div class="bg-shape bg-shape-2"></div>
      <div class="bg-shape bg-shape-3"></div>
    </div>

    <div class="auth-container">
      <!-- 左侧装饰区域 -->
      <div class="auth-banner">
        <div class="banner-content">
          <div class="banner-icon">🚀</div>
          <h1>开始管理您的图书</h1>
          <p>创建账户，轻松管理个人藏书</p>
          <div class="banner-steps">
            <div class="step-item">
              <div class="step-number">1</div>
              <span>注册账户</span>
            </div>
            <div class="step-item">
              <div class="step-number">2</div>
              <span>添加图书</span>
            </div>
            <div class="step-item">
              <div class="step-number">3</div>
              <span>轻松管理</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧注册表单 -->
      <div class="auth-form-container">
        <div class="auth-form">
          <div class="form-header">
            <h2>创建新账户</h2>
            <p>请填写以下信息完成注册</p>
          </div>

          <!-- 错误信息提示 -->
          <div v-if="errorMessage" class="error-alert">
            <div class="error-icon">⚠️</div>
            <span>{{ errorMessage }}</span>
          </div>

          <form @submit="handleSubmit" class="register-form">
            <div class="form-group">
              <label class="form-label">用户名</label>
              <div class="input-wrapper">
                <el-icon class="input-icon"><User /></el-icon>
                <input
                    type="text"
                    v-model="user.username"
                    placeholder="请输入用户名（至少3位）"
                    class="form-input"
                    required
                    :disabled="loading"
                />
                <div v-if="user.username.length >= 3" class="input-success">
                  <el-icon><Check /></el-icon>
                </div>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">密码</label>
              <div class="input-wrapper">
                <el-icon class="input-icon"><Lock /></el-icon>
                <input
                    type="password"
                    v-model="user.password"
                    placeholder="请输入密码（至少6位）"
                    class="form-input"
                    required
                    :disabled="loading"
                    @input="onPasswordChange"
                />
              </div>
              <!-- 密码强度指示器 -->
              <div v-if="user.password" class="password-strength">
                <div class="strength-bar">
                  <div
                      class="strength-fill"
                      :class="`strength-${passwordStrength}`"
                      :style="{ width: `${(passwordStrength / 4) * 100}%` }"
                  ></div>
                </div>
                <span class="strength-text">
                  {{ passwordStrength === 0 ? '弱' : passwordStrength === 1 ? '一般' : passwordStrength === 2 ? '良好' : passwordStrength >= 3 ? '强' : '' }}
                </span>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">确认密码</label>
              <div class="input-wrapper">
                <el-icon class="input-icon"><Lock /></el-icon>
                <input
                    type="password"
                    v-model="user.confirmPassword"
                    placeholder="请再次输入密码"
                    class="form-input"
                    required
                    :disabled="loading"
                />
                <div v-if="user.confirmPassword && user.password === user.confirmPassword" class="input-success">
                  <el-icon><Check /></el-icon>
                </div>
              </div>
            </div>

            <button
                type="submit"
                class="submit-btn"
                :disabled="loading"
                :class="{ 'loading': loading }"
            >
              <span v-if="!loading" class="btn-content">
                <span>立即注册</span>
                <el-icon class="btn-icon"><ArrowRight /></el-icon>
              </span>
              <span v-else class="btn-loading">
                <div class="loading-spinner"></div>
                <span>注册中...</span>
              </span>
            </button>
          </form>

          <div class="form-footer">
            <div class="divider">
              <span>已有账号？</span>
            </div>
            <button @click="goToLogin" class="link-btn">
              立即登录
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 继承登录页面的基础样式 */
.auth-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.bg-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.bg-shape-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.bg-shape-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 20%;
  animation-delay: 2s;
}

.bg-shape-3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 60%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.auth-container {
  max-width: 1000px;
  width: 100%;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: grid;
  grid-template-columns: 1fr 1fr;
  min-height: 650px;
}

.auth-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 60px 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  position: relative;
}

.banner-content {
  text-align: center;
  max-width: 300px;
}

.banner-icon {
  font-size: 64px;
  margin-bottom: 24px;
  display: block;
}

.banner-content h1 {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 16px;
  line-height: 1.2;
}

.banner-content p {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 40px;
  line-height: 1.6;
}

.banner-steps {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 14px;
  opacity: 0.9;
}

.step-number {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.auth-form-container {
  padding: 60px 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.auth-form {
  width: 100%;
  max-width: 320px;
}

.form-header {
  text-align: center;
  margin-bottom: 32px;
}

.form-header h2 {
  font-size: 28px;
  font-weight: 700;
  color: #2d3748;
  margin-bottom: 8px;
}

.form-header p {
  color: #718096;
  font-size: 14px;
}

.error-alert {
  background: #fed7d7;
  color: #c53030;
  padding: 12px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 24px;
  font-size: 14px;
}

.error-icon {
  font-size: 16px;
}

.register-form {
  margin-bottom: 32px;
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 8px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 16px;
  color: #a0aec0;
  font-size: 18px;
  z-index: 2;
}

.input-success {
  position: absolute;
  right: 16px;
  color: #38a169;
  font-size: 18px;
  z-index: 2;
}

.form-input {
  width: 100%;
  padding: 16px 48px 16px 48px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #f7fafc;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  background: white;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input:disabled {
  background: #f1f5f9;
  cursor: not-allowed;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background: #e2e8f0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
  border-radius: 2px;
}

.strength-1 { background: #f56565; }
.strength-2 { background: #ed8936; }
.strength-3 { background: #38a169; }
.strength-4 { background: #38a169; }

.strength-text {
  font-size: 12px;
  color: #718096;
  min-width: 32px;
}

.submit-btn {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
}

.submit-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.btn-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-icon {
  font-size: 16px;
}

.btn-loading {
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.form-footer {
  text-align: center;
}

.divider {
  margin-bottom: 16px;
  color: #718096;
  font-size: 14px;
}

.link-btn {
  background: none;
  border: none;
  color: #667eea;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.link-btn:hover {
  background: rgba(102, 126, 234, 0.1);
  color: #5a67d8;
}

@media (max-width: 768px) {
  .auth-container {
    grid-template-columns: 1fr;
    max-width: 400px;
  }

  .auth-banner {
    padding: 40px 20px;
    min-height: auto;
  }

  .banner-content h1 {
    font-size: 24px;
  }

  .banner-steps {
    flex-direction: row;
    justify-content: center;
    flex-wrap: wrap;
  }

  .auth-form-container {
    padding: 40px 20px;
  }
}
</style>